package org.algorithm.wE1.链表;

import sun.applet.Main;

/**
 * good luck guys
 * keep learing for algorithm
 *
 * @Link {https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/}
 */
public class 反转链表 {
    public static void main(String[] args) {
        int[] score = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        Node head = initNode(score);
        Node newHead = reverse(head);
        System.out.println(printList(newHead));
    }

    /**
     * 翻转
     * @param head
     * @return
     */
    private static Node reverse(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node pre = null;
        //这里是保存下原来的链表head、也可以直接用head
        Node curr = head;
        while (curr != null) {
            Node next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

    /**
     * 输出链表
     * @param head 头节点
     */
    private static String printList(Node head) {
        Node current = head;
        StringBuilder sb = new StringBuilder();
        while (current != null) {
            sb.append(current.val).append("\t");
            current = current.next;
        }
        return sb.toString();
    }

    /**
     * 节点
     */
    static class Node {
        private int val;
        private Node next;

        Node(int val) {
            this.val = val;
            this.next = null;
        }
    }

    /**
     * 初始化链表
     * @param arr
     * @return
     */
    private static Node initNode(int[] arr) {
        Node head = null;
        Node curr = null;
        for (int i = 0; i < arr.length; i++) {
            Node newNode = new Node(arr[i]);
            if (i == 0) {
                head = newNode;
                curr = head;
            } else {
                curr.next = newNode;
                curr = newNode;
            }
        }
        return head;
    }
}
